import { get } from "./api";

export const notificationService = {
  getNotifications: async () => {
    const response = await get("/users/notifications?limit=5");

    // 情况1：如果是字符串数组（["通知1", "通知2", ...]）
    if (Array.isArray(response)) {
      console.warn("通知数据为字符串数组，格式化中：", response);
      return {
        items: response.map((text) => ({
          type: "message",
          title: text,
          time: formatTime(new Date()),
          message: text,
          bgClass: getBgClass("message"),
        })),
        unreadCount: response.length,
      };
    }

    // 情况2：非预期格式，防止崩溃
    if (!response || !Array.isArray(response.items)) {
      console.warn("通知数据格式异常，返回空数组：", response);
      return {
        items: [],
        unreadCount: 0,
      };
    }

    // 情况3：标准格式 { items: [], unread_count: 3 }
    return {
      items: response.items.map((item) => ({
        type: item.type || "message",
        title: item.title || "新通知",
        time: formatTime(item.created_at),
        message: item.content || "",
        bgClass: getBgClass(item.type),
      })),
      unreadCount: response.unread_count || 0,
    };
  },
};

function formatTime(timestamp) {
  const now = new Date();
  const date = new Date(timestamp);
  const diffMins = Math.floor((now - date) / (1000 * 60));
  if (diffMins < 60) return `${diffMins} 分钟前`;
  const diffHours = Math.floor(diffMins / 60);
  if (diffHours < 24) return `${diffHours} 小时前`;
  return date.toLocaleDateString();
}

function getBgClass(type) {
  const map = {
    message: "bg-success",
    alert: "bg-warning",
    system: "bg-info",
  };
  return map[type] || "bg-primary";
}
